#!/usr/bin/env python 
# -*- coding:utf-8 -*-

from django.shortcuts import redirect
from django.conf import settings
from django.contrib.sessions.models import Session
from userprofile.models import GlobalSetting
from userprofile.tests import get_user_permission, get_login_permission
import re

# userOnlinelimit = 0
#
#
# def change_userOnlinelimit():
#     userOnlinelimit = int(GlobalSetting.objects.first().userOnlineLimit)


class LoginRequiredMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.login_url = settings.LOGIN_URL
        self.open_urls = [self.login_url] + get_login_permission()
        self.home_url = '/'
        self.user_permission_urls = [self.home_url, '/get_navlist/', '/UserInfo/',
                                     '/changePassword/'] + get_user_permission() + self.open_urls
        print(self.user_permission_urls)
        # change_userOnlinelimit()

    def __call__(self, request):
        if not request.user.is_authenticated and request.path_info not in self.open_urls:
            return redirect(self.login_url + '?next=' + request.path)

        # print(request.user.is_superuser)
        if not request.user.is_superuser and request.path_info not in self.user_permission_urls and not re.match(
                '/media', request.path_info) and not re.match('/static', request.path_info):
            return redirect(self.home_url + '?next=' + request.path)
        return self.get_response(request)
